import React,{useEffect, useState} from 'react'
import { MemberEntity } from '../model/member'
import { getMembersCollection } from '../api/memberApi'

const useMembersCollection = () => {
    const [membersCollection,setMembersCollection] = 
        useState<MemberEntity[]>([])

    const loadMembersCollection = () => {
        getMembersCollection()
            .then(
                membersCollection => setMembersCollection(
                    membersCollection
                )
            )
    }
    return {
        membersCollection,
        loadMembersCollection
    }
}

const MemberTableComponent:React.FC<{}> = () => {
    // 自定义hooks
    const { membersCollection,loadMembersCollection } = 
        useMembersCollection();
    
    useEffect(() => {
        loadMembersCollection();
    },[])

    return (
        <>
        <table>
            <thead>
                <tr>
                    <th>Avatar</th>
                    <th>id</th>
                    <th>name</th>
                </tr>
            </thead>
            <tbody>
                {
                    membersCollection.map(member => (
                        <MemberRow key={member.id} 
                        member={member}/>
                    ))
                }
            </tbody>
        </table>
        </>
    )
}

const MemberRow = ({member}:{member:MemberEntity}) => (
    <tr>
        <td>
            <img 
                src={member.avatar_url} 
                style={{maxWidth:"10rem"}}
                alt=""
            />
        </td>
        <td>
            <span>{member.login}</span>
        </td>
    </tr>
)

export default MemberTableComponent